package com.langshixiaobai.admin.common.filter;

import cn.hutool.json.JSONUtil;
import com.langshixiaobai.admin.common.constant.UserConstant;
import com.langshixiaobai.admin.common.convention.exception.ClientException;
import com.langshixiaobai.admin.common.utils.UserContext;
import com.langshixiaobai.admin.dao.entity.UserInfoDTO;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.*;

import static com.langshixiaobai.admin.common.enums.UserErrorCodeEnum.USER_ERROR_LOGIN;


/**
 * 用户信息传输过滤器
 *
 * @公众号：马丁玩编程，回复：加群，添加马哥微信（备注：12306）获取项目资料
 */

@Component
public class UserTransmitFilter implements Filter {

    @Autowired
    public RedissonClient redissonClient;


    private final static Set<String> URI = new LinkedHashSet<>();
    // 用于排除URI
    static {
        URI.add("/admin/userLogin");
        URI.add("/admin/getUserInfo");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //TODO 后续开发
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String username = request.getHeader("username");
        String requestURI = request.getRequestURI();
        // 此次URI为过滤标签
        if(!URI.contains(requestURI)) {
            // 用户userId 需要传入
            if (StringUtils.hasText(username)) {
                String token = request.getHeader("token");
                RMap<String, String> map = redissonClient.getMap(UserConstant.USER_Login_KEY);
                String value = map.get(token);
                // 用户未登入
                if(!StringUtils.hasText(value)){
                    throw new ClientException(USER_ERROR_LOGIN);
                }
                UserInfoDTO userInfoDTO = JSONUtil.toBean(value, UserInfoDTO.class);
                // 放入
                UserContext.setUser(userInfoDTO);
            }
        }
        try {
            filterChain.doFilter(request, response);
        } finally {
            UserContext.removeUser();

        }

    }
}
